package com.jade.store.wechat.service.impl;

import com.jade.bss.db.impl.BaseFacadeImpl;
import com.jade.framework.base.context.ApplicationContextUtils;
import com.jade.store.wechat.biz.protocol.WechatAppAutoPush;
import com.jade.store.wechat.biz.service.WxAppPushService;
import com.jade.store.wechat.dao.WechatAppPushDao;
import com.jade.store.wechat.entity.WechatApp;
import com.jade.store.wechat.entity.WechatAppPush;
import com.jade.store.wechat.entity.WechatQrcode;
import com.jade.store.wechat.entity.WechatUser;
import com.jade.store.wechat.service.WechatAppFacade;
import com.jade.store.wechat.service.WechatAppPushFacade;
import com.jade.store.wechat.service.WechatQrcodeFacade;
import com.jade.store.wechat.service.WechatUserFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 被授权的微信公众号推送
 * User: JinYa 2009_jinya@163.com
 * Date: 2016-5-5
 * Time: 10:53
 * Version : 1.0
 * Remark:
 * History:
 */
@Service("WechatAppPushFacade")
public class WechatAppPushFacadeImpl extends BaseFacadeImpl implements WechatAppPushFacade {
    @Inject
    @Named("WechatAppPushDao")
    private WechatAppPushDao wechatAppPushDao;

    private WechatQrcodeFacade wechatQrcodeFacade = ApplicationContextUtils.getBean("WechatQrcodeFacade");
    private WechatUserFacade wechatUserFacade = ApplicationContextUtils.getBean("WechatUserFacade");
    private WechatAppFacade wechatAppFacade = ApplicationContextUtils.getBean("WechatAppFacade");
    @Transactional(propagation= Propagation.REQUIRED)
    public WechatAppPush AutoPush(HttpServletRequest request,String appid,HttpServletResponse resp) throws Exception {
        WechatAppAutoPush entity= WxAppPushService.getReceiveauthcode(request);
        WechatAppPush appPush=new WechatAppPush();
        appPush.setAppId(appid);
        appPush.setToUserName(entity.getToUserName());
        appPush.setFromUserName(entity.getFromUserName());
        appPush.setMsgType(entity.getMsgType());
        if(entity.getMsgType().equals("event")){
            appPush.setCreateTime(entity.getCreateTime());
            appPush.setLongitude(entity.getLongitude());
            appPush.setLatitude(entity.getLatitude());
            appPush.setAddresPrecision(entity.getPrecision());
            appPush.setEvent(entity.getEvent());
            if(entity.getEventKey()!=null && StringUtils.isNotEmpty(entity.getEventKey()))
                appPush.setEventKey(entity.getEventKey().replace("qrscene_", ""));
            appPush.setTicket(entity.getTicket());
            wechatAppPushDao.save(appPush);
            // 1 关注/取消关注事件
            if(appPush.getEvent().equals(WechatAppPush.PUSH_SUBSCRIBE)){//用户关注
                WechatUser oldWechatUser=wechatUserFacade.getWechatUser(appid, appPush.getFromUserName());
                if(oldWechatUser!=null && oldWechatUser.getId()>0){
                    appPush.setWechatUser(oldWechatUser);
                    oldWechatUser.setSubscribe("1");
                    oldWechatUser.setModifyTime(new Date());
                    wechatUserFacade.update(oldWechatUser);
                    appPush.setWechatUser(oldWechatUser);
                }else{
                    WechatUser wechatUser=wechatUserFacade.getWxUser(appid, appPush.getFromUserName());
                    WechatApp wechatApp=wechatAppFacade.getLatestWechatAppByAppID(appid);
                    if(StringUtils.isNotEmpty(appPush.getEventKey())){
                        WechatQrcode wechatQrcode=wechatQrcodeFacade.getQrcodeByEventKey(appPush.getEventKey());
                        if(wechatQrcode!=null && wechatQrcode.getId()>0){
                            wechatUser.setOwnerId(wechatQrcode.getOwnerId());
                            wechatUser.setCreator(wechatQrcode.getCreator());
                            wechatUser.setCreatorId(wechatQrcode.getCreatorId());
                        }
                    }else {
                        wechatUser.setOwnerId(wechatApp.getOwnerId());
                        wechatUser.setCreator(wechatApp.getCreator());
                        wechatUser.setCreatorId(wechatApp.getCreatorId());
                    }
                    wechatUser.setEventKey(appPush.getEventKey());
                    appPush.setWechatUser(wechatUser);
                    wechatUserFacade.save(wechatUser);
                }
            }
            if(appPush.getEvent().equals(WechatAppPush.PUSH_UNSUBSCRIBE)){//取消关注事件
                WechatUser wechatUser=wechatUserFacade.getWechatUser(appid, appPush.getFromUserName());
                if(wechatUser!=null && wechatUser.getId()>0){
                    appPush.setWechatUser(wechatUser);
                    wechatUser.setSubscribe("0");
                    wechatUser.setModifyTime(new Date());
                    wechatUserFacade.update(wechatUser);
                }
            }
            if(appPush.getEvent().equals(WechatAppPush.PUSH_SCAN)){//用户已经关注并且扫码重新加入    // 2 扫描带参数二维码事件
                WechatQrcode wechatQrcode=wechatQrcodeFacade.getQrcodeByEventKey(appPush.getEventKey());
                if(wechatQrcode!=null && wechatQrcode.getId()>0){
                    WechatUser wechatUser=wechatUserFacade.getWechatUser(appid, appPush.getFromUserName());//获得历史的微信用户
                    if(wechatUser==null){
                        WechatUser newUser=wechatUserFacade.getWxUser(appid,appPush.getFromUserName());
                        wechatUser.setOwnerId(wechatQrcode.getOwnerId());
                        wechatUser.setCreator(wechatQrcode.getCreator());
                        wechatUser.setCreator(wechatQrcode.getCreator());
                        wechatUserFacade.save(newUser);
                        appPush.setWechatUser(newUser);
                    }else{
                        wechatUser.setOwnerId(wechatQrcode.getOwnerId());
                        wechatUser.setCreator(wechatQrcode.getCreator());
                        wechatUser.setCreator(wechatQrcode.getCreator());
                        appPush.setWechatUser(wechatUser);
                    }
                }
            }
            if(appPush.getEvent().equals(WechatAppPush.PUSH_LOCATION)){//地图定位      //3 上报地理位置事件

            }
            if(appPush.getEvent().equals(WechatAppPush.PUSH_CLICK)){//点击菜单拉取消息时的事件推送   //4 自定义菜单事件    //5 点击菜单拉取消息时的事件推送

            }
            if(appPush.getEvent().equals(WechatAppPush.PUSH_VIEW)){//点击菜单拉取消息时的事件推送    //6 点击菜单跳转链接时的事件推送

            }
        }else if(entity.getMsgType().equals("text")){
            appPush.setCreateTime(entity.getCreateTime());
            appPush.setContent(entity.getContent());
            appPush.setMsgId(entity.getMsgId());
            appPush.setCreateTime(entity.getCreateTime());
            wechatAppPushDao.save(appPush);
            keyReply(appPush,resp);
        } else if(entity.getMsgType().equals("image")){
            appPush.setCreateTime(entity.getCreateTime());
            appPush.setPicUrl(entity.getPicUrl());
            appPush.setMediaId(entity.getMediaId());
            appPush.setMsgId(entity.getMsgId());
            wechatAppPushDao.save(appPush);
        }else if(entity.getMsgType().equals("voice")){
            appPush.setCreateTime(entity.getCreateTime());
            appPush.setFormat(entity.getFormat());
            appPush.setMediaId(entity.getMediaId());
            appPush.setMsgId(entity.getMsgId());
            wechatAppPushDao.save(appPush);
        }else if(entity.getMsgType().equals("video")){
            appPush.setCreateTime(entity.getCreateTime());
            appPush.setThumbMediaId(entity.getThumbMediaId());
            appPush.setMediaId(entity.getMediaId());
            appPush.setMsgId(entity.getMsgId());
            wechatAppPushDao.save(appPush);
        }else if(entity.getMsgType().equals("shortvideo")){
            appPush.setCreateTime(entity.getCreateTime());
            appPush.setThumbMediaId(entity.getThumbMediaId());
            appPush.setMediaId(entity.getMediaId());
            appPush.setMsgId(entity.getMsgId());
            wechatAppPushDao.save(appPush);
        }else if(entity.getMsgType().equals("location")){
            appPush.setCreateTime(entity.getCreateTime());
            appPush.setLocation_X(entity.getLocation_X());
            appPush.setLocation_Y(entity.getLocation_Y());
            appPush.setScale(entity.getScale());
            appPush.setLabel(entity.getLabel());
            appPush.setMsgId(entity.getMsgId());
            wechatAppPushDao.save(appPush);
        }else if(entity.getMsgType().equals("link")){
            appPush.setCreateTime(entity.getCreateTime());
            appPush.setLocation_X(entity.getLocation_X());
            appPush.setTitle(entity.getTitle());
            appPush.setDescription(entity.getDescription());
            appPush.setUrl(entity.getUrl());
            appPush.setMsgId(entity.getMsgId());
            wechatAppPushDao.save(appPush);
        }
        return appPush;
    }

    /**
     * 关注回复
     * @param resp
     */
    public  void subscribeReply(HttpServletResponse resp) throws Exception{

    }
    /**
     * 扫描回复
     * @param resp
     */
    public  void scanReply(HttpServletResponse resp) throws Exception{

    }
    /**
     * 关键字回复
     * @param resp
     */
    public  void keyReply(WechatAppPush appPush,HttpServletResponse resp) throws Exception{
        /*ReplyText replyText=new ReplyText();
        //解决XStream对出现双下划线的bug
        XStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
        replyText.setMsgType(replyText.getMsgType());
        replyText.setContent("欢迎您使用");
        replyText.setFromUserName(appPush.getToUserName());
        replyText.setToUserName(appPush.getFromUserName());
        replyText.setCreateTime(Calendar.getInstance().getTimeInMillis());
        //将要提交给API的数据对象转换成XML格式数据Post给API
        String postDataXML = xStreamForRequestPostData.toXML(replyText);
        OutputStream out = resp.getOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(out);
        writer.write(postDataXML);
        writer.close();//这行必须写，否则无法输出响应正文*/
    }
}
